package com.time.workshop.ui;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.time.workshop.API;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.bean.RequestOrder;
import com.time.workshop.bean.ResponseShopDetail;
import com.time.workshop.bean.ShopList;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.LaoBanDialog;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.OnClickOKListener;

@SuppressLint("SimpleDateFormat")
public class WantDingZuoActivity extends SuperActivity implements
		OnClickListener {
	@V
	private ListView xlistView;
	@V
	private ImageView img_login_back;
	@V
	private RelativeLayout info_Layout, time_Layout, peoplecount_Layout,
			name_Layout, phone_Layout, remarks_Layout;
	@V
	private LinearLayout infoTexts_Layout;
	@V
	private TextView commitOrderTextView, timeTextView, shopNameTextView,
			shopAddrTextView, advancePriceTextView;
	@V
	private EditText nameEditText, phoneEditText, remarksEditText,
			peoplecountEditText;
	@V
	private ScrollView scrollview;
	@V
	private ImageView infoImageView;

	private DatePicker datePicker;
	private TimePicker timePicker;
	private AlertDialog dialog;
	public Calendar time = Calendar.getInstance(Locale.CHINA);
	private boolean processFlag = true;

	private LaoBanDialog dlg;
	private String storeId = "";
	private String order_no = "";
	private ShopList shopList;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_want_dingzuo);

		init();
	}

	private void init() {
		Injector.getInstance().inject(this);
		img_login_back.setOnClickListener(this);
		commitOrderTextView.setOnClickListener(this);
		time_Layout.setOnClickListener(this);
		info_Layout.getBackground().setAlpha(229);// 90%透明度
		time_Layout.getBackground().setAlpha(204);// 80%透明度
		peoplecount_Layout.getBackground().setAlpha(178);// 70%透明度
		name_Layout.getBackground().setAlpha(153);// 60%透明度
		phone_Layout.getBackground().setAlpha(127);// 50%透明度
		remarks_Layout.getBackground().setAlpha(102);// 40%透明度
		commitOrderTextView.getBackground().setAlpha(153);// 60%透明度
		infoTexts_Layout.getBackground().setAlpha(235);// 10%透明度

		scrollview.setBackgroundResource(R.drawable.bg);

		setView();

	}

	private void setView() {
		shopList = (ShopList) getIntent().getSerializableExtra("shoplist");
		shopNameTextView.setText(shopList.getNAME());
		shopAddrTextView.setText(shopList.getADDRESS());
		advancePriceTextView.setText(shopList.getPRICE()+"元起");

		ImageLoader.getInstance().displayImage(shopList.getPIC_URL(), infoImageView, getDisplayOption());
		requestDetail(shopList.getID());
	}

	private void requestDetail(String id) {
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.GET, API.shopDetail + "?id=" + id,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						try {
							if (responseInfo.result != null) {
								Gson gson = new Gson();
								ResponseShopDetail detail = gson.fromJson(
										responseInfo.result,
										ResponseShopDetail.class);
								shopNameTextView.setText(detail.NAME);
								shopAddrTextView.setText(detail.ADDRESS);
								advancePriceTextView.setText(detail.PRICE+"元起");
								ImageLoader.getInstance().displayImage(
										detail.PIC_URL, infoImageView,
										getDisplayOption());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println(msg);
					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_login_back:
			CommonUtils.hide(this);
			back();
			break;
		case R.id.commitOrderTextView:
			if (check()) {
				showConfirmDialog();
			}
			break;
		case R.id.time_Layout:
			if (processFlag == true) {
				dateTimePickerDialog();
				processFlag = false;
				new TimeThread().start();
			}
			break;

		default:
			break;
		}
	}

	/**
	 * 显示 Dailog
	 */
	private void showConfirmDialog() {

		dlg = new LaoBanDialog(WantDingZuoActivity.this);
		if (dlg.isShowing()) {
			dlg.dismiss();
			return;
		}
		dlg.onCreate();
		dlg.setOnClickOK(new OnClickOKListener() {

			@Override
			public void setOnClickOK() {
				submitOrder();

			}
		});

	}

	private void dismisMyDialog() {

		if (dlg != null && dlg.isShowing()) {
			dlg.dismiss();
		}
		dlg = null;

	}

	private void submitOrder() {

		// ORDER_TYPE:订单类型(GHDD:挂号;LCWDD:遛宠物;LRDS:老人专区打扫;LRMC:老人专区买菜;
		// LRPL:老人专区陪聊;PPDD:陪跑:TCDD:同城;WMDD:外卖;YDDD:订座)
		// token:登录token
		// remark:备注
		// contactor_person：联系人姓名
		// contactor_phone：联系电话
		// reservation_time:订座时间
		// reservation_person:订座人数
		// contactor_address:联系地址
		// store_id：店铺ID
//		Intent in = new Intent(WantDingZuoActivity.this,
//				ConfirmOrderActivity.class);
//		in.putExtra("remark", remarksEditText.getText().toString().trim());
//		in.putExtra("name", nameEditText.getText().toString().trim());
//		in.putExtra("phone", phoneEditText.getText().toString().trim());
//		in.putExtra("dingzuotime", timeTextView.getText().toString().trim());
//		in.putExtra("dingzuomun", peoplecountEditText.getText().toString().trim());
//		in.putExtra("store_id", shopList.getID());
//		in.putExtra("price", shopList.getPRICE());
//		startActivity(in, true);
//		finish();
		dlg.dismiss();
		RequestOrder requestOrder = new RequestOrder();
		requestOrder.ORDER_TYPE = "YDDD";
		requestOrder.contactor_person = nameEditText.getText().toString().trim();
		requestOrder.contactor_phone = phoneEditText.getText().toString().trim();
		requestOrder.remark = remarksEditText.getText().toString().trim();
		requestOrder.reservation_time = timeTextView.getText().toString().trim();
		requestOrder.reservation_person = peoplecountEditText.getText().toString().trim();
		requestOrder.store_id = shopList.getID();
		requestOrder.price = shopList.getPRICE();
		API.submitOrder(requestOrder, WantDingZuoActivity.this);
	}

	// 选择时间
	public AlertDialog dateTimePickerDialog() {
		LinearLayout dateTimeLayout = (LinearLayout) LayoutInflater.from(this)
				.inflate(R.layout.date_time_picker, null);
		datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.DatePicker);
		timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.TimePicker);
		timePicker.setIs24HourView(true);

		OnTimeChangedListener timeListener = new OnTimeChangedListener() {
			@Override
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
				time.set(Calendar.HOUR_OF_DAY, hourOfDay);
				time.set(Calendar.MINUTE, minute);

			}
		};

		timePicker.setOnTimeChangedListener(timeListener);
		OnDateChangedListener dateListener = new OnDateChangedListener() {

			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				time.set(Calendar.YEAR, year);
				time.set(Calendar.MONTH, monthOfYear);
				time.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			}
		};

		datePicker.init(time.get(Calendar.YEAR), time.get(Calendar.MONTH),
				time.get(Calendar.DAY_OF_MONTH), dateListener);
		timePicker.setCurrentHour(time.get(Calendar.HOUR_OF_DAY));
		timePicker.setCurrentMinute(time.get(Calendar.MINUTE));

		dialog = new AlertDialog.Builder(this)
				.setTitle("设置日期时间")
				.setView(dateTimeLayout)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						time.set(Calendar.YEAR, datePicker.getYear());
						time.set(Calendar.MONTH, datePicker.getMonth());
						time.set(Calendar.DAY_OF_MONTH,
								datePicker.getDayOfMonth());
						time.set(Calendar.HOUR_OF_DAY,
								timePicker.getCurrentHour());
						time.set(Calendar.MINUTE, timePicker.getCurrentMinute());
						SimpleDateFormat format = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						timeTextView.setText(format.format(time.getTime()));
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).show();
		return dialog;
	}

	private class TimeThread extends Thread {
		public void run() {
			try {
				Thread.sleep(2000);
				processFlag = true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		dismisMyDialog();
	}
	
	private boolean check() {
		if (CommonUtils.isNull_nie(timeTextView.getText().toString().trim())||
				timeTextView.getText().toString().trim().equals(getResources().getString(R.string.laoren_hint_time))) {
			NewToast.makeText(getApplicationContext(),"用餐时间不能为空");
			return false;
		} else if (CommonUtils.isNull_nie(peoplecountEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"用餐人数不能为空");
			return false;
		}else if (CommonUtils.isNull_nie(nameEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"姓名不能为空");
			return false;
		}else if (CommonUtils.isNull_nie(phoneEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"电话不能为空");
			return false;
		}else if (!CommonUtils.isMobile(phoneEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"电话号码格式错误");
			return false;
		}else {
			return true;
		}
	}
	
}
